﻿Imports System.Windows.Forms
Imports Runa.Core.GamePackage
Imports Runa.Common.Helper
Imports System.Collections

Public NotInheritable Class FormLoading

    Private m_loaded As Boolean = False

    Private Sub FormLoading_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If Me.m_loaded = False Then
            'Dim games = g_fileStorage.GetDirectories()
            'For Each g In games
            '    g_fileStorage.DeleteDirectory(g, True)
            'Next
            Debuger.TraceListener.WriteLine("Warning: the extraction of games may have not been finished successfully.")
        End If
    End Sub

    Private Sub FormLoading_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
        Me.BW.RunWorkerAsync()
    End Sub

    Private Sub BW_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BW.DoWork
        Dim lst As New List(Of GamePackageBase)
        Dim games = g_fileStorage.GetDirectories()
        For Each g In games
            Try
                lst.Add(New RunaGamePackage(g, g_fileStorage))
            Catch ex As Exception
                Debuger.TraceListener.WriteLine(String.Format("{0}: {1}" & vbCrLf, Now.ToString(), ex.Message, ex.StackTrace.ToString()))
            End Try
        Next
        Me.BW.ReportProgress(30)
        games = g_fileStorage.GetFiles()
        For i As Integer = 0 To games.Count - 1
            Try
                Dim g = games(i)
                Me.BW.ReportProgress(CInt(Math.Ceiling((i / games.Count) * 50)) + 30)
                If lst.Contains(Function(item) item.Name.ToLower() = g) Then
                    Continue For
                Else
                    lst.Add(New RunaGamePackage(g, g_fileStorage))
                End If
            Catch ex As Exception
                Debuger.TraceListener.WriteLine(String.Format("{0}: {1}" & vbCrLf, Now.ToString(), ex.Message, ex.StackTrace.ToString()))
            End Try
        Next
        For i As Integer = 0 To g_externalFiles.Count - 1
            Try
                Dim g = g_externalFiles(i)
                Dim name = Path.GetFileNameWithoutExtension(g)
                Me.BW.ReportProgress(CInt(Math.Ceiling((i / g_externalFiles.Count) * 20)) + 80)
                If lst.Contains(Function(item) item.Name.ToLower() = name) Then
                    lst.RemoveIf(Function(item) item.Name.ToLower() = name)
                End If
                Using fs As New FileStream(g, IO.FileMode.Open)
                    lst.Add(New RunaGamePackage(name, fs, g_fileStorage))
                End Using
            Catch ex As Exception
                Debuger.TraceListener.WriteLine(String.Format("{0}: {1}" & vbCrLf, Now.ToString(), ex.Message, ex.StackTrace.ToString()))
            End Try
        Next
        Me.BW.ReportProgress(100)
        e.Result = lst
    End Sub

    Private Sub BW_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BW.ProgressChanged
        Me.PB_Progress.Value = e.ProgressPercentage
    End Sub

    Private Sub BW_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BW.RunWorkerCompleted
        If e.Cancelled Then
            MessageBox.Show("Loading task has been cancelled.")
        ElseIf e.Error IsNot Nothing Then
            MessageBox.Show(e.Error.Message & vbCrLf & e.Error.StackTrace.ToString())
        Else
            g_gameList = CType(e.Result, List(Of GamePackageBase))
            Try
#If DEBUG Then
                FormGameChooser.Show()
                Me.Hide()
#Else
                If g_gameList.Count = 1 Then
                    Dim thr As New System.Threading.Thread(New Threading.ParameterizedThreadStart(
                        Sub(gn)
                            Using game As New GameRender(g_gameList.Where(Function(obj) obj.Name = gn.ToString())(0))
                                AddHandler game.Shown,
                                    Sub()
                                        Me.BeginInvoke(
                                            Sub()
                                                Me.Hide()
                                                Me.m_loaded = True
                                            End Sub)
                                    End Sub
                                game.Run()
                            End Using
                            Application.Exit()
                        End Sub))
                    thr.Start(g_gameList.First().Name)
                Else
                    FormGameChooser.Show()
                    Me.Hide()
                End If
#End If
            Catch ex As Exception
                MessageBox.Show(ex.Message & vbCrLf & ex.StackTrace.ToString())
            End Try
        End If
    End Sub

End Class